package com.venutech.gongan.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.PageUtils;
import com.shihang.misc.date.DateTimeUtil;
import com.venutech.gongan.common.BusinessException;
import com.venutech.gongan.dao.BarCodeMapper;
import com.venutech.gongan.dto.rpc.common.vo.ServerWorkDto;
import com.venutech.gongan.entity.BarCode;
import com.venutech.gongan.service.BarCodeService;
import com.venutech.gongan.util.BarcodeUtil2;
import com.venutech.gongan.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class BarCodeServiceImpl implements BarCodeService {

    Logger logger = LoggerFactory.getLogger(EquipmenServiceImpl.class);

    @Resource
    private BarCodeMapper barCodeMapper;

    @Resource
    BarCodeService barCodeService;

    @Value("${barcode.save-dir}")
    String barCodeSaveDir;

    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public int createBarCodeWithFile(BarCode barCode) throws IOException {
        insert(barCode);
        int bc_id = barCode.getBc_id();

        //MD5
        String bcIdMD5 = MD5Util.MD5Encode(String.valueOf(bc_id), "UTF-8");
        String codeContent=String.format("bc_id=%s", bcIdMD5);
        //条形码物理保存地址
        File codeImgFileSaveDir = new File(barCodeSaveDir);
        //20编码 SN+运营商+序列
        String bc_bm="";
        String sn = barCode.getBc_sn();
        System.out.println("SN==========================="+sn);
        //运营商编码
        String yys=barCode.getBc_yys();

        /*
        //序列
        int sevenSeq=barCodeService.getSevenSeq();
        //1 SN转换
        //SN百度纯数字+长度9位
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        boolean flag = pattern.matcher(sn).matches();
        //字符串中是否包含交换机华为
        int jhj = sn.indexOf("S6");
        //字符串中是否包含 310Y
        int huawei = sn.indexOf("310Y");
        if (flag && sn.length()==9){
            bc_bm=sn+"-"+yys+"-"+sevenSeq;
        }
        //长度不满9位
        else if (flag && sn.length()<9){
            int zro=9-sn.length();
            String zros="";
            for (int i = 0; i <zro ; i++) {
                zros+="0";
            }
            bc_bm=(zros+sn)+"-"+yys+"-"+sevenSeq;
        }
        //SN百度纯数字+长度大于9位
        else if (flag && sn.length()>9) {
            //从后面截取9位
            sn=sn.substring(sn.length()-9);
            bc_bm=sn+"-"+yys+"-"+sevenSeq;
        }
        else if (sn.equals("S6720")){
            //从后面截取9位
            sn = "0000S6720";
            bc_bm=sn+"-"+yys+"-"+sevenSeq;
        }
        else if (huawei>0){
            //从后面截取9位
            sn = sn.substring(sn.length()-9);
            bc_bm=sn+"-"+yys+"-"+sevenSeq;
        }
        String picId = UUID.randomUUID().toString()+sn;
        picId=picId.substring(picId.lastIndexOf('-')+1)+".png";
*/
        String year = DateTimeUtil.getTodayDate("yyyyMMdd").substring(2,4);
        String paddingZeroId = paddingZeroFromLeft(String.valueOf(bc_id), 5);
        bc_bm = String.format("%s-%s-%s", year, yys, paddingZeroId);

        //调用条码生成并返回文件名称picId
        String[] arr = bc_bm.split("-");
        String newSN="";
        for (int i = 0; i <arr.length ; i++) {
            newSN+=arr[i];
        }
        String picId = newSN + ".png";

        BarCode newBarCode = getById(bc_id);
        newBarCode.setBc_id_md5(bcIdMD5);
        newBarCode.setBc_bm(bc_bm);
        newBarCode.setBc_picid(picId);
        newBarCode.setReal_code(newSN);
        updateBarCode(newBarCode);

        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:static/barcodebg.png");
        if(!resource.exists()) {
            throw new BusinessException(String.format("bgImgfile not exists [%s]", resource.getURL()));
        }
        int length = (int)resource.contentLength();
        byte[] fileData = new byte[length];
        resource.getInputStream().read(fileData);
        BarcodeUtil2.inputMsg2(newSN, new File(barCodeSaveDir), picId, fileData);

        return bc_id;
    }

    private String paddingZeroFromLeft(String no, int paddings) {
        while (no.length() < paddings) {
            no = "0" + no;
        }
        return no;
    }


    @Override
    public int insert(BarCode barCode) {
//        Integer insert = barCodeMapper.insert(barCode);
//        if (insert > 0) {
//            return ResultUtil.success();
//        }else {
//            return ResultUtil.error(100,"添加失败");
//        }
        return barCodeMapper.insert(barCode);
    }

    @Override
    public int deleteById(Integer bc_id) {
        return barCodeMapper.deleteById(bc_id);
    }

    @Override
    public int updateBarCode(BarCode barCode) {
        System.err.println(barCode.getReal_code());
        return barCodeMapper.updateBarCode(barCode);
    }

    @Override
    public BarCode getById(Integer bc_id) {
        return barCodeMapper.getById(bc_id);
    }

    @Override
    public Integer getLastSeq() {
        return barCodeMapper.getLastSeq();
    }

    @Override
    public Integer getSevenSeq() {
        return barCodeMapper.getSevenSeq();
    }

    @Override
    public Page<BarCode> getInfo(Integer pageNo, Integer pageSize, String begintime, String endtime, String badw, String bc_sn) {
        Page<BarCode> page = new Page<>(pageNo,pageSize);
        PageUtils.startPage();
        List<BarCode> list = barCodeMapper.getInfo(begintime,endtime,badw,page,bc_sn);
        page.setTotal(new PageInfo<>(list).getTotal());
        return page.setRecords(list);
    }

    /**
     * 根据二维码id来获取设备所有数据
     * @param bcid
     * @return
     */
    @Override
    public BarCode getBarcodeInfo(String bcid) {
        return barCodeMapper.getBarcodeInfo(bcid);
    }

    /**
     * 条形码上报事件
     * @param
     * @return
     */
    @Override
    public int getEvénementworkSheet(ServerWorkDto poleDto) {
        return barCodeMapper.getEvénementworkSheet(poleDto);
    }

}
